package com.vivebest.utils.common.utils;

import com.vivebest.utils.common.constant.MsgConstants;
import com.vivebest.utils.common.dto.CmdResponseDto;
import com.vivebest.utils.common.exception.BizException;
import lombok.extern.log4j.Log4j2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * <p>
 *     命令行执行工具类
 * </p>
 * @author zsk
 * @date 2020/8/10 下午2:27
 */
@Log4j2
public class CmdUtils {

    /**
     * shell解释器
     */
    private final static String PROCESS_SH ="/bin/sh";
    /**
     * shell参数
     */
    private final static String PROCESS_ARGS ="-c";

    /**
     * 执行shell命令
     * @param cmd shell命令
     * @return cmd执行结果
     * @throws IOException cmd执行结果读取异常
     */
    public static CmdResponseDto processCmd(String cmd) throws IOException {
        String[] cmdSh = new String[]{PROCESS_SH, PROCESS_ARGS, cmd};
        Process ps = Runtime.getRuntime().exec(cmdSh);

        int exitValue= 0;
        try {
            exitValue = ps.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String result;
        if(exitValue==0){
            result=ioToString(ps.getInputStream());
        }else {
            result=ioToString(ps.getErrorStream());
        }

        return CmdResponseDto
                .builder()
                .result(result)
                .exitValue(exitValue)
                .build();
    }

    /**
     * 执行shell命令
     * @param cmd shell命令
     * @return cmd执行结果
     * @throws IOException cmd执行结果读取异常
     */
    public static void processCmdUnWaitFor(String cmd) throws IOException {
        String[] cmdSh = new String[]{PROCESS_SH, PROCESS_ARGS, cmd};
        Runtime.getRuntime().exec(cmdSh);

    }

    private static String ioToString(InputStream inputStream) {
        BufferedReader br= new BufferedReader(new InputStreamReader(inputStream));
        return br.lines()
                .reduce((s, s2) -> s+=s2+"\n")
                .orElseThrow(()->new BizException(MsgConstants.COMM100003));
    }

}
